<?php

namespace App\Store\Controllers\Financial\Statements;

use App\Common\Services\CommonExcelExport;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
use App\Common\Services\Store\Common as StoreCommon;
use App\Http\Controllers\Controller;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Financial\Statements\Moneylog as FinancialMoneylog;
use Illuminate\Http\Request;
use App\Store\Validate\Financial\Statements\Moneylog as ValidateMoneylog;

/**
 * 日记账
 */
class MoneylogController extends Controller
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {

        $params = [];
        $params['store_id'] = intval($request->store_id);

        if ($params['store_id'] <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择门店']);
        }

        $type = $request->type;
        if (!in_array($type, [1, 2, 3])) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $list = FinancialMoneylog::getList($request, $type);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    public function getinfo(Request $request)
    {
        $type = $request->type;
        if (!in_array($type, [1, 2, 3])) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $id = $request->id ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info = FinancialMoneylog::where(['id' => $id, 'is_del' => 1, 'type' => $type, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['store_id', 'type', 'abstract', 'inout_type', 'receipt_type', 'log_date', 'pay_type_id', 'receipt_no', 'subject_id', 'income_money', 'expenditure_money', 'residue_money', 'remark']);

        $Validate = new ValidateMoneylog;
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];
        if (in_array($accountinfo['type'], [1, 2, 3])) {
            if ($accountinfo['type'] == 3) {
                if (is_array($store_ids) && isset($req_data['store_id']) && in_array($req_data['store_id'], $store_ids)) {
                    $current_store_id = intval($req_data['store_id']);
                } else {
                    return response()->json(['code' => '001', 'msg' => '财务端操作请选择门店']);
                }


            } else {
                $current_store_id = intval($store_ids);
            }


        } else {
            return response()->json(['code' => '001', 'msg' => '请使用财务、店长或店员账号']);
        }

        $data = $req_data;
        $data['receipt_type'] = !empty($req_data['receipt_type']) ? $req_data['receipt_type'] : 0;
        $data['cp_id'] = $cp_id;
        $data['store_id'] = $current_store_id;
        $data['log_date'] = date('Y-m-d', strtotime($data['log_date']));
        $data['create_at'] = time();
        $data['update_at'] = time();
        $data['create_account_id'] = $accountinfo['id'];
        $data['create_account_real_name'] = $accountinfo['real_name'];
        $data['update_account_id'] = $accountinfo['id'];
        $data['update_account_real_name'] = $accountinfo['real_name'];
        FinancialMoneylog::create($data);
        return response()->json(['code' => '000', 'msg' => '新增日记账成功']);
    }

    public function dopostedit(Request $request)
    {
        $req_data = $request->only(['id', 'store_id', 'type', 'log_date', 'abstract', 'pay_type_id', 'receipt_no', 'subject_id', 'income_money', 'expenditure_money', 'residue_money', 'remark', 'inout_type', 'receipt_type']);

        $Validate = new ValidateMoneylog('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];


        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];
        if (in_array($accountinfo['type'], [1, 2, 3])) {
            if ($accountinfo['type'] == 3) {
                if (is_array($store_ids) && isset($req_data['store_id']) && in_array($req_data['store_id'], $store_ids)) {
                    $current_store_id = intval($req_data['store_id']);
                } else {
                    return response()->json(['code' => '001', 'msg' => '财务端操作请选择门店']);
                }


            } else {
                $current_store_id = intval($store_ids);
            }


        } else {
            return response()->json(['code' => '001', 'msg' => '请使用财务、店长或店员账号']);
        }

        $info = FinancialMoneylog::where(['id' => $req_data['id'], 'is_del' => 1, 'type' => $req_data['type'], 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $data = $req_data;
        $data['store_id'] = $current_store_id;
        $data['log_date'] = date('Y-m-d', strtotime($data['log_date']));
        $data['update_at'] = time();
        $data['update_account_id'] = $accountinfo['id'];
        $data['update_account_real_name'] = $accountinfo['real_name'];
        FinancialMoneylog::where(['id' => $req_data['id'], 'is_del' => 1])->update($data);
        return response()->json(['code' => '000', 'msg' => '编辑日记账成功']);
    }

    public function dopostdel(Request $request)
    {
//        $type=$request->type;
//        if(!in_array($type,[1,2,3])){
//            return response()->json(['code' => '001', 'msg' => '参数错误']);
//        }
        $id = $request->id ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = FinancialMoneylog::where(['id' => $id, 'is_del' => 1, 'cp_id' => $cp_id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        FinancialMoneylog::where(['id' => $id])->update(['is_del' => 2, 'del_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    protected function getmoneylogcount($type, $receipt_type, $cp_id)
    {
        $log_date_s = date('Y-m') . '-01';
        $where['cp_id']=$cp_id;
        $where['type']=$type;
        $count = FinancialMoneylog::query()
            ->where($where)
            ->where('log_date','>=',$log_date_s)
            ->where('inout_type','>',0)
            ->count();
        $count += 1;
        return ['count' => $count, 'no' => date('n') . '-' . $count . '#'];
    }


    public function doexport(Request $request)
    {
        /**
         * 科目：销售收入，收入
         * 科目：销售费用，支出
         */
        $subject_name_arr = ['-1' => '销售收入', '-2' => '销售费用', '-3' => '销售费用-商品维修费', '-4' => '销售费用-广告费和业务宣传费', '-5' => '财务费用-手续费'];
        $type = $request->type;
        if (!in_array($type, [1, 2, 3])) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $list = FinancialMoneylog::getList($request, $type)['list'];

        $title = ($type == 1 ? '现金' : ($type == 2 ? '银行' : '储值卡')) . '日记账';

        $exceldata = [];
        $store_name = SiteStore::where(['id' => intval($request->store_id)])->value('store_name');
        $row = [
            ['log_date' => $title],
            ['log_date' => '所属门店：' . $store_name],
            [
                'log_date' => '日期',
                'receipt_no' => '收据号',
                'abstract' => '摘要',
                'subject_name' => '科目',
                'income_money' => '收入金额',
                'expenditure_money' => '支出金额',
                'residue_money' => '余额',
                'remark' => '备注',
            ]
        ];
        foreach ($list as $val) {
            if ($val['inout_type'] == 0) {
                $exceldata[] = [
                    'log_date' => '',
                    'receipt_no' => '',
                    'abstract' => $val['abstract'],
                    'subject_name' => '',
                    'income_money' => $val['income_money'] / 100,
                    'expenditure_money' => $val['expenditure_money'] / 100,
                    'residue_money' => $val['residue_money'] / 100,
                    'remark' => '',
                ];
            } else {
                $exceldata[] = [
                    'log_date' => $val['log_date'],
                    'receipt_no' => $val['receipt_no'],
                    'abstract' => $val['abstract'],
                    'subject_name' => $val['subject_id'] < 0 ? $subject_name_arr[$val['subject_id']] : ($val['subjectinfo'] ? $val['subjectinfo']['subject_name'] : ''),
                    'income_money' => $val['income_money'] / 100,
                    'expenditure_money' => $val['expenditure_money'] / 100,
                    'residue_money' => $val['residue_money'] / 100,
                    'remark' => $val['remark'],
                ];
            }

        }

        $filename = $title . '信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    public function getlastmoneylog(Request $request)
    {
        $type = $request->type;
        if (!in_array($type, [1, 2, 3])) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];
        if (is_array($store_ids) || $store_ids == '' || $store_ids <= 0) { //获取当前权限下的门店

            return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
        } else {
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }

        $last_moneylog = FinancialMoneylog::where(['type' => $type, 'store_id' => $current_store_id, 'is_del' => 1, 'cp_id' => $cp_id])->orderBy('id', 'desc')->first();
        $last_moneylog_residue_money = $last_moneylog ? $last_moneylog->residue_money : 0;

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['last_moneylog_residue_money' => $last_moneylog_residue_money]]);
    }

    public function getmoneylogcountbyday(Request $request)
    {
        $type = $request->type;
        if (!in_array($type, [1, 2, 3])) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $log_date_s = date('Y-m') . '-01';

        // $count = FinancialMoneylog::where([['type',$type],['log_date','>=',$log_date_s]])->count();
        // //是否返回receipt_no
        // return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['count'=>$count]]);
        $receipt_type = intval($request->receipt_type);
        $data = $this->getmoneylogcount($type, $receipt_type, $cp_id);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $data]);
    }

    /**
     * 日记账数据修改
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateMoneyLog(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'income_money' => 'sometimes',
            'expenditure_money' => 'sometimes',
            'abstract' => 'sometimes'
        ], [
            'id.required' => 'ID必填',
        ]);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        if ($validator->fails()) {
            $msg = $validator->errors()->first();
            return response()->json(['code' => '001', 'msg' => $msg]);
        }
        $params = $validator->validated();

        $data = [];

        $abstract = $params['abstract'] ?? '';
        if (isset($params['income_money'])) {
            $data['income_money'] = $params['income_money'];
        }
        if (isset($params['expenditure_money'])) {
            $data['expenditure_money'] = $params['expenditure_money'];
        }

        if (!empty($abstract)) {
            $data['abstract'] = $abstract;
        }
        $log = FinancialMoneylog::query()
            ->where(['id' => $params['id'], 'is_del' => 1, 'cp_id' => $cp_id])
            ->first();
        if (empty($log)) {
            return response()->json(['code' => '001', 'msg' => '数据不存在无法修改']);
        }

        $log = $log->toArray();

        $previousId = FinancialMoneylog::query()
            ->where(['is_del' => 1, 'cp_id' => $cp_id,'type'=>$log['type'],'store_id'=>$log['store_id']])
            ->where('id','<',$params['id'])
            ->max('id');


        $previous =FinancialMoneylog::query()
            ->where(['is_del' => 1, 'cp_id' => $cp_id,'type'=>$log['type'],'id'=>$previousId,'store_id'=>$log['store_id']])
            ->first();
        $previous =empty($previous)?[]:$previous->toArray();

        $firstDayOfMonth = date('Y-m-01');
        $lastDayOfMonth = date('Y-m-t');

        $logDate = strtotime($log['log_date']);
        $firstDayOfMonth = strtotime($firstDayOfMonth);
        $lastDayOfMonth = strtotime($lastDayOfMonth);

        if ($logDate > $lastDayOfMonth || $logDate < $firstDayOfMonth) {
            return response()->json(['code' => '001', 'msg' => '只能修改当月的数据']);
        }
        if (!empty($data['income_money']) && !empty($params['expenditure_money'])) {
            return response()->json(['code' => '001', 'msg' => '收入和支出只能编辑一个']);
        }

        $residue_money = ($previous['residue_money']??0)+ ($data['income_money'] ?? $log['income_money']) - ($data['expenditure_money'] ?? $log['expenditure_money']);

        if (!empty($data)) {
            //先不进行核算只修改数据
            FinancialMoneylog::query()
                ->where(['id' => $params['id'], 'is_del' => 1, 'cp_id' => $cp_id])
                ->update($data);
        }

        if (!empty($data['income_money']) || !empty($params['expenditure_money'])) {
            //需要重新计算当月的值
            $logList = FinancialMoneylog::query()
                ->where(['is_del' => 1, 'cp_id' => $cp_id,'type'=>$log['type'],'store_id'=>$log['store_id']])
                ->where('inout_type','>',0)
                ->where('id', '>=', $log['id'])
                ->get()
                ->toArray();
          $total=0;
          foreach ($logList as $key=>&$item) {
              $item['residue_money'] = $residue_money;

              if ($key>=1) {
                  $nextMoney = $residue_money;
                  if($total==0){
                      $total+= $nextMoney + $item['income_money'] - $item['expenditure_money'];
                  }else{
                     // echo $total.'--'.$item['income_money'].'--'.$item['expenditure_money'].'/';
                      $total= $total + $item['income_money'] - $item['expenditure_money'];
                  }

                  $item['residue_money']=$total;
              }
          }

          foreach ($logList as $val){
              FinancialMoneylog::query()
                  ->where('id', $val['id'])
                  ->update(['residue_money'=>$val['residue_money']]);
          }

        }
        return response()->json(['code' => '000', 'msg' => '修改成功']);
    }
}
